package com.linewow.xhyy.nihaonew.view;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.base.VoiceMenuBase;
import com.linewow.xhyy.nihaonew.inter.RecorderInter;
import com.linewow.xhyy.nihaonew.view.input.MenuVoiceRecorder;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by LXR on 2016/9/4.
 */
public class VoiceMenu extends VoiceMenuBase {
    @Bind(R.id.view_add_voice_time_minute)
    TextView viewAddVoiceTimeMinute;
    @Bind(R.id.view_add_voice_time_second)
    TextView viewAddVoiceTimeSecond;
    @Bind(R.id.view_add_voice_mic)
    ImageView viewAddVoiceMic;
    @Bind(R.id.view_add_voice_play)
    ImageView viewAddVoicePlay;
    @Bind(R.id.view_add_voice_press)
    TextView viewAddVoicePress;
    @Bind(R.id.view_add_voice_click)
    TextView viewAddVoiceClick;
    @Bind(R.id.view_add_voice_commit)
    TextView viewAddVoiceCommit;
    @Bind(R.id.view_add_voice_recording)
    ImageView viewAddVoiceRecording;


    private String TAG = "VoiceMenu";
    protected MenuVoiceRecorder voiceRecorder;
    private Timer timerPause, timerPlay;
    private int pauseSecond;
    private int voiceTime;
    private MediaPlayer mediaPlayer;
    private String path;
    private int playSecond;
    private static boolean isPause;
    public boolean isPlaying;
    private boolean isFinish = true;
    private long time1;
    private RecorderInter pathSure;

    private boolean switchFlag;

    public void setPathSure(RecorderInter pathSure) {
        this.pathSure = pathSure;
    }

    public VoiceMenu(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    public VoiceMenu(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public VoiceMenu(Context context) {
        super(context);
        init(context);
    }

    public void setPath(String name) {

        voiceRecorder.setPathName(name);
    }

    private void init(final Context context) {
        layoutInflater.inflate(R.layout.view_add_voice, this);
        ButterKnife.bind(this);
        voiceRecorder = new MenuVoiceRecorder(handler);
        Glide.with(context).load(R.mipmap.icon_mic_ing).into(viewAddVoiceRecording);
        viewAddVoicePress.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startRecording();
                        time1 = System.currentTimeMillis();
                        Log.e(TAG, "手指按下了" + time1);
                        viewAddVoiceRecording.setVisibility(VISIBLE);
                        break;
                    case MotionEvent.ACTION_UP:
                        stopRecording();
                        long time2 = System.currentTimeMillis();
                        Log.e(TAG, "手指放开" + time2);
                        if ((time2 - time1) < 1000) {
                            reStartRecorder();
                            Toast.makeText(context, "时间太短，请重录", Toast.LENGTH_SHORT).show();
                        } else {
                            //录音成功了
                            pathSure.commitFinish(path);
                        }
                        viewAddVoiceRecording.setVisibility(GONE);
                        break;
                }
                return false;
            }
        });
    }


    @OnClick({R.id.view_add_voice_click, R.id.view_add_voice_play})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.view_add_voice_click:
                reStartRecorder();
                break;
            case R.id.view_add_voice_play:
                if (isPlaying) {
                    pausePlay();
                } else {
                    startPlay();
                }
                break;

        }
    }


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 200) {
                pauseSecond++;
                showTime(pauseSecond);
            } else if (msg.what == 201) {
                playSecond++;
                showTime(playSecond);
            }
        }
    };

    private void pausePlay() {
        isPlaying = false;
        isPause = true;
        viewAddVoicePlay.setImageResource(R.mipmap.icon_voice_play);
        if (mediaPlayer != null) {
            mediaPlayer.pause();
        }
    }


    private void startPlay() {
        viewAddVoicePlay.setImageResource(R.mipmap.icon_voice_pause);
        isPause = false;
        isPlaying = true;
        if (!isFinish) {
            mediaPlayer.start();
            return;
        }
        isFinish = false;
        Log.e(TAG, "开始播放了");
        showTime(0);
        timerPlay = new Timer();
        timerPlay.schedule(new TimerTask() {
            @Override
            public void run() {
                if (!isPause) {
                    Log.e(TAG, "播放递增");
                    handler.sendEmptyMessage(201);
                }

            }
        }, 1000, 1000);
        mediaPlayer = new MediaPlayer();
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        audioManager.setSpeakerphoneOn(false);
        audioManager.setMode(AudioManager.MODE_IN_CALL);
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
        try {
            mediaPlayer.setDataSource(path);
            mediaPlayer.prepare();
            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    mediaPlayer.release();
                    mediaPlayer = null;
                    viewAddVoicePlay.setImageResource(R.mipmap.icon_voice_play);
                    timerPlay.cancel();
                    playSecond = 0;
                    isPlaying = false;
                    isFinish = true;

                    showTime(voiceTime);

                }
            });
            mediaPlayer.start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void reStartRecorder() {

        sendCancel();
        pauseSecond = 0;
        playSecond = 0;
        stopPlay();
        viewAddVoiceCommit.setVisibility(View.GONE);
        viewAddVoiceMic.setVisibility(View.VISIBLE);
        viewAddVoicePlay.setVisibility(View.GONE);
        viewAddVoicePlay.setImageResource(R.mipmap.icon_voice_play);
        viewAddVoicePress.setVisibility(View.VISIBLE);
        viewAddVoiceClick.setVisibility(View.GONE);
        if (timerPlay != null) {
            timerPlay.cancel();
        }
        if (timerPause != null) {
            timerPause.cancel();
        }
        showTime(0);
    }


    private void stopRecording() {
        Log.e(TAG, "停止录音了");
        timerPause.cancel();
        if(switchFlag){
            viewAddVoiceCommit.setVisibility(View.VISIBLE);
        }else{
            viewAddVoiceCommit.setVisibility(View.GONE);
        }
        try {
            voiceTime = voiceRecorder.stopRecoding();
        }catch (Exception e){
            Log.e(TAG,"崩溃了");
        }
        viewAddVoiceClick.setVisibility(View.VISIBLE);
        viewAddVoicePress.setVisibility(View.GONE);
        viewAddVoiceMic.setVisibility(View.GONE);
        viewAddVoicePlay.setVisibility(View.VISIBLE);
        viewAddVoicePlay.setImageResource(R.mipmap.icon_voice_play);
        pauseSecond = voiceTime;
        showTime(pauseSecond);
    }

    private void stopPlay() {
        isPlaying = false;
        isPause = false;
        isFinish = true;
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }

    }

    public void setSwitchFlag(boolean switchFlag) {
        this.switchFlag = switchFlag;
    }

    private void startRecording() {
        pauseSecond = 0;
        timerPause = new Timer();
        path = voiceRecorder.startRecording(context);
        timerPause.schedule(new TimerTask() {
            @Override
            public void run() {
                Log.e(TAG, "录音递增");
                handler.sendEmptyMessage(200);
            }
        }, 1000, 1000);
    }


    private void showTime(int second) {
        int minute = second / 60;
        int sec = second % 60;
        String s1 = (minute < 10) ? ("0" + minute) : ("" + minute);
        String s2 = (sec < 10) ? ("0" + sec) : ("" + sec);
        viewAddVoiceTimeSecond.setText(s2);
        viewAddVoiceTimeMinute.setText(s1);
    }

    @OnClick(R.id.view_add_voice_commit)
    public void onClick() {
        sendSuccess();

    }

    public void sendSuccess(){
        pathSure.pathFinish(true);

    }
    //和重新录制的逻辑 不完全一样
    public void reset(){
        pauseSecond = 0;
        playSecond = 0;
        stopPlay();
        viewAddVoiceCommit.setVisibility(View.GONE);
        viewAddVoiceMic.setVisibility(View.VISIBLE);
        viewAddVoicePlay.setVisibility(View.GONE);
        viewAddVoicePlay.setImageResource(R.mipmap.icon_voice_play);
        viewAddVoicePress.setVisibility(View.VISIBLE);
        viewAddVoiceClick.setVisibility(View.GONE);
        if (timerPlay != null) {
            timerPlay.cancel();
        }
        if (timerPause != null) {
            timerPause.cancel();
        }
        showTime(0);
    }
    public void sendCancel(){
        pathSure.pathFinish(false);
    }
}
